<?php

namespace App\Console\Commands;

use DB;
use Illuminate\Console\Command;
use App\Http\Controllers\common\LoraController;
use App\Http\Controllers\common\EmailController;
use App\Http\Controllers\common\VoiceController;
use App\Http\Controllers\common\YunpianController;
//模型
use App\Models\Area;
use App\Models\Building;
use App\Models\Room;
use App\Models\Notiset;

class GWS extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'GWS';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //$fp = @fopen("D:/phpStudy/www/test.txt", "a+");
        $info = DB::table('gateway as gw')
            -> leftJoin('room as r','gw.room_id','=','r.id')
            -> leftJoin('building as b','r.building_id','=','b.id')
            -> leftJoin('area as a','b.area_id','=','a.id')
            -> leftJoin('model as m','gw.model_id','=','m.id')
            -> select('gw.name','gw.GatewayID','gw.room_id','gw.loc','gw.status','r.name as room_name','r.building_id','b.name as building_name','b.area_id','a.name as area_name')
            -> get();
        //获取区域负责人手机号
        foreach ($info as $val){
            //获取网关状态
            if($val['status'] == 1){
                $status = $this -> getGatewayStatus($val['GatewayID']);
                if(!$status){
                    $phone = '';
                    $e = '';
                    //查询通知设置表
                    $notiSet = Notiset::all() -> toArray();
                    //获取手机号
                    if($notiSet[0]['noti_area'] == 1){$phone .= $this -> getMode('area',$val['area_id'])['phone'];}
                    if($notiSet[0]['noti_building'] == 1){$phone .= ','.$this -> getMode('building',$val['building_id'])['phone'];}
                    if($notiSet[0]['noti_room'] == 1){$phone .= ','.$this -> getMode('room',$val['room_id'])['phone'];}
                    $phones = implode(',',array_unique(explode(',',$phone)));
                    //获取邮箱
                    if($notiSet[2]['noti_area'] == 1){$e .= $this -> getMode('area',$val['area_id'])['email'];}
                    if($notiSet[2]['noti_building'] == 1){$e .= ','.$this -> getMode('building',$val['building_id'])['email'];}
                    if($notiSet[2]['noti_room'] == 1){$e .= ','.$this -> getMode('room',$val['room_id'])['email'];}
                    $emails = array_unique(explode(',',$e));
                    //发送短信
                    $msgCnt = '尊敬的用户，您位于'.$val['area_name'].$val['building_name'].$val['room_name'].$val['loc'].'的'.$val['name'].'网关处于离线状态，请及时处置！';
                    //$this -> sendMessage($phones,$msgCnt);
                    //发送语音
                    $voiceCnt = '105842;q:'.$val['area_name'].$val['building_name'].$val['room_name'].$val['loc'].',w:'.$val['name'].'网关处于离线状态';
                    $options = ['certpath'=>'D:/phpStudy/WWW/newqy/public'];
                    //$res = $this -> sendVoice($phones,$voiceCnt,$options);
                    //发送邮箱
                    $email = ['user'=>$emails,'title'=>'网关离线通知'];
                    $user = ['area'=>$val['area_name'].$val['building_name'].$val['room_name'].$val['loc'],'num'=>$val['name'],'content'=>'网关处于离线状态，请及时处置！'];
                    //$res = $this -> sendEmail($email,$user);
                    //fwrite($fp, "\n邮箱：" .date("Y-m-d H:i:s").'-'.json_encode($notiSet));
                }
            }
        }
        //fclose($fp);
    }

    //获取管理范围手机号和邮箱
    public function getMode($range,$rangeId){
        $phone = '';
        $email = '';
        switch ($range){
            case 'area':
                $rangeObj = new Area();
                break;
            case 'building':
                $rangeObj = new Building();
                break;
            case 'room':
                $rangeObj = new Room();
                break;
            default:
                $rangeObj = false;
        }
        if($rangeObj){
            $info = $rangeObj -> find($rangeId) -> member() -> select('email','phone') -> get() -> toarray();
            foreach ($info as $v){
                $phone .= $v['phone'].',';
                $email .= $v['email'].',';
            }
            $phone = substr($phone,0,-1);
            $email = substr($email,0,-1);
        }
        return ['phone'=>$phone,'email'=>$email];
    }

    //短信通知
    public function sendMessage($phone,$content){
        $message = new YunpianController();
        $response = $message -> Msgsend($phone,$content);
        return $response;
    }
    //语音通知
    public function sendVoice($phone,$content,$options){
        $voice = new VoiceController();
        $response = $voice -> sendMsg($phone,$content,$options);
        return $response;
    }
    //邮箱通知
    public function sendEmail($email,$user){
        $em = new EmailController();
        $response = $em -> sendEmail($email,$user);
        return $response;
    }

    //获取网关状态
    public function getGatewayStatus($GatewayID){
        $lora = new LoraController();
        $res = $lora -> getGatewayMsg($GatewayID);
        $res = json_decode($res,true);
        if(isset($res['data'])){
            return $res['data']['state'] ;
        }else{
            return 0;
        }
    }
}